package com.insight.modules.cas.controller;

import com.alibaba.fastjson.JSONObject;
import com.yuanqiao.insight.acore.depart.entity.SysDepart;
import com.yuanqiao.insight.common.util.common.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.constant.CommonConstant;
import com.insight.common.system.util.JwtUtil;
import com.insight.modules.cas.util.CASServiceUtil;
import com.insight.modules.cas.util.XmlUtils;
import com.insight.modules.system.entity.SysUsers;
import com.insight.modules.system.service.ISysDepartService;
import com.insight.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * CAS单点登录客户端登录认证
 * </p>
 *
 * @Author zhoujf
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/cas/client")
public class CasClientController {

	@Autowired
	private ISysUserService sysUserService;
	@Autowired
    private ISysDepartService sysDepartService;
	@Autowired
    private RedisUtils redisUtil;

	@Autowired
	private JwtUtil jwtUtil;

	@Value("${cas.prefixUrl}")
    private String prefixUrl;


	@GetMapping("/validateLogin")
	public Object validateLogin(@RequestParam(name="ticket") String ticket,
								@RequestParam(name="service") String service,
								HttpServletRequest request,
								HttpServletResponse response) {
		if (StringUtils.isEmpty(ticket) || StringUtils.isEmpty(service)){
			return Result.error("参数[ticket]和[service]不能为空");
		}
		Result<JSONObject> result = new Result<JSONObject>();
		log.info("Rest api login.");
		try {
			String validateUrl = prefixUrl+"/p3/serviceValidate";
			String res = CASServiceUtil.getSTValidate(validateUrl, ticket, service);
			log.info("res."+res);
			final String error = XmlUtils.getTextForElement(res, "authenticationFailure");
			if(StringUtils.isNotEmpty(error)) {
				return Result.error("认证失败: " + error);
			}
			final String principal = XmlUtils.getTextForElement(res, "user");
			if (StringUtils.isEmpty(principal)) {
				return Result.error("No principal was found in the response from the CAS server.");
			}
			log.info("-------token----username---"+principal);
			//1. 校验用户是否有效
			SysUsers sysUser = sysUserService.getUserByName(principal);
			result = sysUserService.checkUserIsEffective(sysUser);
			if(!result.isSuccess()) {
				return result;
			}
			String token = jwtUtil.sign(sysUser.getUsername(), sysUser.getPassword());
			// 设置token超时过期时间
			redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
			redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, jwtUtil.getTime());

			//获取用户部门信息
			JSONObject obj = new JSONObject();
			List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
			obj.put("departs", departs);
			if (departs == null || departs.size() == 0) {
				obj.put("multi_depart", 0);
			} else if (departs.size() == 1) {
				sysUserService.updateUserDepart(principal, departs.get(0).getOrgCode());
				obj.put("multi_depart", 1);
			} else {
				obj.put("multi_depart", 2);
			}
			obj.put("token", token);
			obj.put("userInfo", sysUser);
			result.setResult(obj);
			result.success("登录成功");

		} catch (Exception e) {
			//e.printStackTrace();
			result.error500(e.getMessage());
		}
		return new HttpEntity<>(result);
	}


}
